package org.jdsm.gae.komarichyn;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ObjectFactory;
import com.opensymphony.xwork2.conversion.impl.DefaultObjectTypeDeterminer;
import com.opensymphony.xwork2.conversion.impl.XWorkConverter;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.reflection.ReflectionProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * User: mikom
 * Date: 3/7/13
 * Time: 5:03 PM
 */
public class MyObjectTypeDeterminer extends DefaultObjectTypeDeterminer {

    private static final Logger log = LoggerFactory.getLogger(MyObjectTypeDeterminer.class);

    private ObjectFactory objectFactory;

    @Inject
    public MyObjectTypeDeterminer(@Inject XWorkConverter conv, @Inject ReflectionProvider prov) {
        super(conv, prov);
    }

    @Override
    public Class getElementClass(Class parentClass, String property, Object key) {

        ElementByBeanName annotation = getAnnotation(parentClass, property, ElementByBeanName.class);
        if (annotation != null) {
            try {
                Object obj = objectFactory.buildBean(annotation.value(), ActionContext.getContext().getContextMap());
                return obj.getClass();
            } catch (ClassNotFoundException e) {
                log.error("Exception:{}", e.getMessage());
            } catch (Exception e) {
                log.error("Exception:{}", e.getMessage());
            }
        }

        return super.getElementClass(parentClass, property, key);
    }

    @Inject
    public void setObjectFactory(ObjectFactory objectFactory) {
        this.objectFactory = objectFactory;
    }
}
